package com.springmvc.api.interceptor;

import com.springmvc.api.security.IgnoreSecurity;
import org.apache.log4j.Logger;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * Created by cheng.xi on 12/3/15.
 */
public class AuthenticateInterceptor extends HandlerInterceptorAdapter {
    private static Logger LOGGER = Logger.getLogger(AuthenticateInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        LOGGER.info("请求到达，开始进行处理。");
        String host = request.getHeader("X-Forwarded-For");
        if(null == host || "".equals(host.trim())){
            host = request.getRemoteAddr();
        }
        LOGGER.info("请求 host - [" + host + "], requestURI - [" + request.getRequestURI() + "], contentType - [" + request.getContentType() + "]");

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        if(method.isAnnotationPresent(IgnoreSecurity.class)){
            return true;
        }

        String token = request.getHeader("X-Token");
        LOGGER.info("token---------->" + token);
        //token 校验
        return false;
    }
}
